package com.crm.custinfo.service.impl;

import com.crm.custinfo.domain.UserAddmustDetail;
import com.ruoyi.common.constant.ConfigConstant;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import com.ruoyi.common.utils.DateUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;
@Service
public class UserInfoComm {
    @Autowired
    private ISysConfigService baseSysConfigService;

    @Autowired
    private ISysDeptService isysDeptService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private UserAddmustDetailServiceImpl userAddmustDetailService;
    /**
     * 查询当前用户拥有的角色权限
     */
    public Map<String, Object> getUserRoleCode() {
        Map<String, Object> resMap = new HashMap<String, Object>();
        // 根据渠道来源展示开关判断是否展示渠道来源
        String channelShowFlag = baseSysConfigService.getItemValueByItemKey(ConfigConstant.CHANNEL_SOURCE_SHOW_FLAG, "1");
        List<SysRole> roleList = getLoginUser().getUser().getRoles();
        SysDept dept = getLoginUser().getUser().getDept();


        String company_leader = "0"; // 是否公司总负责人角色 1-是 0-否
        String sub_leader = "0"; // 是否分公司总负责人角色 1-是 0-否
        String suborg_leader = "0"; // 是否分公司负责人角色 1-是 0-否
        String area_leader = "0"; // 一级部门经理
        String depart_leader = "0"; // 二级部门经理
        String is_financial = "0"; //是否财务
        String is_xingzheng = "0"; // 是否行政
        String is_emp = "0"; // 是否业务员
        String is_xuetu = "0"; // 是否学徒
        String is_channeler = "0"; // 是否运营
        String chl_leader = "0";// 是否渠道部长
        String is_xingzheng_leader = "0"; // 是否行政部长
        String is_store_manager = "0"; // 是否门店长

        for (SysRole sysRole : roleList) {
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_1)||sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_00)) {
                company_leader = "1";
                sub_leader = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_2)) {
                sub_leader = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_3)) {
                area_leader = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_4) || sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_40)) {
                depart_leader = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_5) || sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_8)) {
                // 学徒角色权限同业务员
                is_emp = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_6) || sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_106)) {
                is_xingzheng = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_106)) {
                is_xingzheng_leader = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_7)) {
                is_financial = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_8)) {
                is_xuetu = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_10)) {
                is_channeler = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_98) || sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_100) || sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_108)) {
                suborg_leader = "1";
            }
            if (sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_105)) {
                chl_leader = "1";
            }
            if(sysRole.getRoleKey().equals(TypeConstant.ROLE_ID_100)){
                is_store_manager="1";
            }
        }


        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("chl_leader", chl_leader);
        roleMap.put("is_channeler", is_channeler);
        roleMap.put("suborg_leader", suborg_leader);
        roleMap.put("is_xingzheng", is_xingzheng);
        roleMap.put("is_xingzheng_leader", is_xingzheng_leader);
        roleMap.put("is_financial", is_financial);
        roleMap.put("company_leader", company_leader);
        roleMap.put("sub_leader", sub_leader);
        roleMap.put("area_leader", area_leader);
        roleMap.put("depart_leader", depart_leader);
        roleMap.put("is_emp", is_emp);
        roleMap.put("is_xuetu", is_xuetu);
        roleMap.put("channelShowFlag", channelShowFlag);
        roleMap.put("is_store_manager", is_store_manager);
        roleMap.put("dept_level", dept.getLevel());
        roleMap.put("dept_company_id()", dept.getCompanyId());



        resMap.putAll(roleMap);
//        resMap.put("company_id", ConfigProperties.get("company.id", 0));
        // 记录redis提升性能
        //RedisClientUtil.setRedisKeyVal(RedisConstant.KEY_ROLE_MAP + user.getRoleId(), JSONUtils.toJSONString(roleMap));
        return resMap;
    }

    /**
     * 是否分公司级别以上
     *
     * @param resMap
     * @return
     */
    public boolean isCompanyBoss(Map<String, Object> resMap) {
        boolean is_company_leader = MapUtils.getIntValue(resMap, "company_leader", 0) == 1;
        boolean is_sub_leader = MapUtils.getIntValue(resMap, "sub_leader", 0) == 1;
        if (!(is_company_leader || is_sub_leader)) {
            return false;
        }
        return true;
    }


    /**
     * 查询当前部门所属总公司-最大级别
     *
     * @param orgId
     * @return
     */
    public long getCurentCompanyOrgId(long orgId) {

        SysDept curOrg = isysDeptService.selectDeptById(orgId);
        if (curOrg == null) {
            return -1l;
        }
        while (curOrg.getParentId() > 0) {
            curOrg = isysDeptService.selectDeptById(curOrg.getParentId());
        }
        return curOrg.getDeptId();
    }

    /**
     * 查询当前部门所属分公司-第2大级别
     *
     * @param orgId
     * @return
     */
    public long getCurentSubCompanyOrgId(long orgId) {
        SysDept curOrg = isysDeptService.selectDeptById(orgId);
        if (curOrg == null) {
            return -1l;
        }
        while (curOrg.getAncestors().split(",").length > 1) {

            curOrg = isysDeptService.selectDeptById(curOrg.getParentId());
        }
        return curOrg.getDeptId();
    }

    /**
     * 查询当前用户可操作的所有部门-重载
     *
     * @param user
     * @param queryType 1-标识总负责人角色判断
     * @return
     */
    public List<SysDept> findAllOrgsUnderUser(SysUser user, String queryType) {
        if (StringUtils.isNotBlank(queryType) && queryType.equals("1")) {
            if (isCompanyLeader(user)) {// 查询所有分公司
                return getOrgListUnderOrgId(0l);
            }
        }
//        Boolean isRole100 = false;
//        List<SysRole> roles = user.getRoles();
//        for (SysRole role : roles) {
//            if (TypeConstant.ROLE_ID_100.equals(role.getRoleKey())) {
//                isRole100 = true;
//                break;
//            }
//        }
//
//        if (isRole100) {
//            // 门店长查询管辖的部门
//            List<SysDept> list = new ArrayList<>();
//            Long[] orgIds = user.getRoleIds();
//            for (Long orgId : orgIds) {
//                list.addAll(isysDeptService.selectChildrenDeptById(orgId));
//            }
//            return list;
//        } else {
//            // 其他用户默认查自己当前所属部门
//            return isysDeptService.selectDeptById(user.getDeptId());
//        }
        return isysDeptService.selectChildrenAllDeptById(user.getDeptId());
    }

    /**
     * 判断是否公司总负责人
     *
     * @param user
     * @return
     */
    public boolean isCompanyLeader(SysUser user) {
        Boolean isRole100 = false;
        List<SysRole> roles = user.getRoles();
        for (SysRole role : roles) {
            if (TypeConstant.ROLE_ID_00.equals(role.getRoleKey())||TypeConstant.ROLE_ID_1.equals(role.getRoleKey())) {
                isRole100 = true;
                break;
            }
        }
        return isRole100;
    }

    //获取部门下的可操作部门列表
    public List<SysDept> getOrgListUnderOrgId(long orgId) {
        if (orgId == 0L) {
            //获取所有分公司
            SysDept sysDept = new SysDept();
            sysDept.setStatus("0");
            sysDept.setDelFlag("0");
            return isysDeptService.selectDeptList(sysDept);
        } else {
            return isysDeptService.selectChildrenAllDeptById(orgId);
        }
    }

    // 查询当日已获取客户数量
    public int getUserDailyFetchDatas(long empId) {
        UserAddmustDetail detail = new UserAddmustDetail();
        detail.setOperType("4");
        detail.setOperDate(DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD) );
        detail.setEmpId(empId);
        List<UserAddmustDetail> details = userAddmustDetailService.selectUserAddmustDetailList(detail);
        if (CollectionUtils.isEmpty(details)) {
            return 0;
        }
        return details.get(0).getCustIds().split(",").length;
    }

    /**
     * 根据部门信息获取用户的empid和deptid集合，用角色去过滤
     * @param sysDeptsList
     * @return
     */
    public Map<String,Object> getDeptIdsEmpIdsByDepts(List<SysDept> sysDeptsList) {
        Map<String,Object> ids_map=new HashMap<String,Object>();
        Long[] deptIds=new Long[sysDeptsList.size()];
        List<Long> usersList=new ArrayList<Long>();
        List<String> listRoleKey=new ArrayList<String>(){};
        listRoleKey.add(TypeConstant.ROLE_ID_3);
        listRoleKey.add(TypeConstant.ROLE_ID_4);
        listRoleKey.add(TypeConstant.ROLE_ID_40);
        listRoleKey.add(TypeConstant.ROLE_ID_5);
        listRoleKey.add(TypeConstant.ROLE_ID_8);

        for (int i=0;i<sysDeptsList.size();i++){
            deptIds[i] = sysDeptsList.get(i).getDeptId();
        }
        Map<String,Object> inparams = new HashMap<String,Object>(){};
        inparams.put("orgIds",deptIds);
        SysUser inSysUser=new SysUser();
        inSysUser.setParams(inparams);
        List<SysUser> sysUserList=iSysUserService.selectUserByDeptids(inSysUser);
        for (SysUser sysUser : sysUserList){
            if(listRoleKey.contains( sysUser.getRoleKey())){
                usersList.add(sysUser.getUserId());
            }
        }
        ids_map.put("deptIds",deptIds);

        ids_map.put("empIds",usersList.toArray(new Long[0]));
        return ids_map ;
    }

    /**
     * 根据部门Id获取部门集合数据
      * @param deptId
     * @return
     */
    public Long[] getDeptIds(Long deptId){
        List<SysDept> deptList = getOrgListUnderOrgId(deptId);
        if(deptList.isEmpty()){
            return null;
        }
        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = new Long[deptList.size()];
        for (int i = 0; i < deptList.size(); i++) {
            SysDept sysDept = deptList.get(i);
            orgIds[i] = sysDept.getDeptId();
        }
        return orgIds;
    }
    //获取权限
    public int getRightType() {
        int right_type=1;
        SysDept sysDept=getLoginUser().getUser().getDept();
        if(String.valueOf(TypeConstant.ORG_LEVEL_4).equals(sysDept.getLevel()) ){
            //判断是否是部门
            right_type = 4;
            List<SysRole> sysRoles = getLoginUser().getUser().getRoles();
            for (SysRole sysRole : sysRoles) {
                if (TypeConstant.ROLE_ID_4.equals(sysRole.getRoleKey()) || TypeConstant.ROLE_ID_40.equals(sysRole.getRoleKey())) {
                    right_type = 3;
                    break;
                }
            }

        }
        return right_type;
    }
    /**
     * 获取权限部门的ids
     * @param sysDept
     * @return
     */
    public Long[] getSysDepts(SysDept sysDept) {
        List<SysDept> sysDepts = isysDeptService.selectChildrenAllDeptById(sysDept.getDeptId());
        Long[] orgIds = new Long[sysDepts.size()];
        for (int i = 0; i < sysDepts.size(); i++) {
            SysDept sysDept2 = sysDepts.get(i);
            orgIds[i] = sysDept2.getDeptId();
        }
        return orgIds;
    }
}
